package com.bruip.reggie.controller;

import com.bruip.reggie.common.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件的上传和下载
 *
 * @author 王若龙
 * @date 2022-10-06 19:56
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return {@link BaseResponse}<{@link String}>
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(MultipartFile file) {
        //file 传输过程中是一个临时文件，完成上传操作后悔自动清除

        //获取上传文件时原始的文件名
        String originalFilename = file.getOriginalFilename();
        //获取原文件名的后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID生成新的文件名，防止文件名重复导致覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        //判断目录是否存在
        File file1 = new File(basePath);
        if (!file1.exists()) {
            //目录不存在，创建目录
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return BaseResponse.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try (
                //文件输入流，读取图片
                FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
                //文件输出流，将图片在浏览器页面显示
                ServletOutputStream outputStream = response.getOutputStream();
        ) {
            response.setContentType("image/jpeg");
            //传输
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
